<?php 

import('@.com.99ebc.lib.Error');
import('@.com.99ebc.lib.File');
import('@.com.99ebc.lib.Xml');

import("ORG.Util.Image");


class ConfigModel{

    protected $_xml; 
    protected static $xmlFilePath   = 'config.xml';

    protected $_imageTypes;
    protected $_imageSize;
    protected $_uploadDir;

    //默认详细信息里显示的图片类型
    protected static $infoImgType     = '_s';
    //格式:width, height, type, interlace, 后缀
    protected static $thumbImgInfo  = array(
        '_s' => array('w' => 100, 'h' => 100, 't' => 'jpg', 'i' => true),
    );


    protected $_error;

    public function __construct() {
        $this->_imageSize   = 20;
        $this->_imageTypes  = array('jpg', 'jpeg', 'png', 'gif', 'bmp', 'mp3');
        $this->_uploadDir   = 'Public/default/uploadfiles/config';
        $this->_error       = new Error(); 
    }

    protected function loadXmlFile() {
        $this->_xml     = simplexml_load_file(self::$xmlFilePath);
    }

    protected function verifyFile() {
        if(!file_exists(self::$xmlFilePath)) {
            Logger::log('文件不存在！' . self::$xmlFilePath);
            return false;
        }

        return true;
    }

    public function txtinfoConfig() {
        if(false === $this->verifyFile()) {
            return false;
        }
        $this->loadXmlFile();

        return $this->genRecordInfo();
    }

    public function txteditConfig() {
        if(false === $this->verifyFile()) {
            return false;
        }
        $this->loadXmlFile();
        $this->editXml();
        
        return $this->decodeHtmlFromFile(self::$xmlFilePath);
    }

    public function uploadConfig() {
        $uploadItems     = array(
            'logo_upload' => 'uploadLogo',
            'bg_upload_1' => 'uploadBgFirst',
            'bg_upload_2' => 'uploadBgSecond',
            'bg_upload_3' => 'uploadBgThird',
            'music_upload'=> 'uploadMusic' 
        );
        $data   = array(
            'status' => 0,
            'path' => '',
            'msg' => ''
        );
        if(empty($_FILES)) {
            $data['msg']    = '文件不能为空！';
            Logger::log($data['msg']);

            return $data;
        }
        foreach($_FILES as $key => $uploadInfo) {
            if(!array_key_exists($key, $uploadItems)) {
                $data['msg'] = '非法操作!';
                Logger::log(var_export($data, true));
            }
            $this->loadXmlFile();
            $actionName     = $uploadItems[$key];
            $targetPath     = $this->$actionName();
            if(empty($targetPath)) {
                $data['msg'] = '上传失败！';
                Logger::log($data['msg']);
            } else {
                $this->_xml->asXml(self::$xmlFilePath);
                $data['status'] = 0;
                $data['msg']    = '上传成功！';
                $data['path']   = preg_replace('/default\//i', '', $this->genThumbImagePath($targetPath));
                Logger::log(var_export($data, true));
            }
        }

        return $data;
    }

    protected function uploadLogo() {
        return $this->commUpload('logo_upload', 'myLogo');
    }

    protected function uploadBgFirst() {
        return $this->commUpload('bg_upload_1', 'backgroundImage1');
    }

    protected function uploadBgSecond() {
        return $this->commUpload('bg_upload_2', 'backgroundImage2');
    }

    protected function uploadBgThird() {
        return $this->commUpload('bg_upload_3', 'backgroundImage3');
    }

    protected function uploadMusic() {
        return $this->commUpload('music_upload', 'myMusic');
    }

    protected function commUpload($fileItem, $item) {
        $uploadFile = $_FILES[$fileItem];
        $oldFile    =  $this->_xml->mods[$item];
        $upload   = $this->uploadFIle($uploadFile);
        if(empty($upload)) {
            return false;
        } else {
            if(!empty($oldFile)) {
                $this->deleteFile($oldFile);
            }
            $this->_xml->mods[$item]    = $upload;
        }

        return $upload;
    }

    protected function editXml() {
        $this->_xml->mods['backgroundMusic']        = $_POST['bg_music'];
        $this->_xml->mods['multipleBackgrounds']    = $_POST['mult_bg'];
        $this->_xml->footerInfo[0]                  = $this->getCompanyInfo();
    }

    protected function getCompanyInfo() {
        $companyInfo    = trim(LittleTools::filterMoreSlashes($_POST['company_info']));
        
        return '<![CDATA[' . $companyInfo . ']]>';
    }

    protected function decodeHtmlFromFile($filePath) {
        //更新联系信息先 
        $this->updateContantInfo();
        
        $xmlContent     = $this->_xml->asXml();
        $xmlContent     = LittleTools::htmlDecode($xmlContent);
        if(($fileHandle = fopen($filePath, 'w'))) {
            if(false === fwrite($fileHandle, $xmlContent)) {
                Logger::log("XML转换HTML标签失败！" . $filePath);
                fclose($fileHandle);
                return false;
            }
            fclose($fileHandle);
            return true;
        }
        Logger::log("XML文件打不开！" . $filePath);


        return false;
    }

    protected function updateContantInfo() {
        $xmlContantFile = 'xml/contactinfo.xml';
        $contactInfo    = '<contactinfo>
    <info>' . $this->getCompanyInfo() . '</info>
    </contactinfo>';
        $xml            = new Xml($xmlContantFile, $contactInfo);

        return $xml->save();
    }

    protected function formatFilePathInTpl($src) {
        return preg_replace(array('/public\//i', '%\/+%'), array('', '/'), $src);
    }

    protected function genRecordInfo() {
        $recordInfo     = array();
        $recordInfo['logo_upload']    = $this->formatFilePathInTpl($this->_xml->mods['myLogo']);
        $recordInfo['bg_upload']    = array(
            $this->formatFilePathInTpl($this->_xml->mods['backgroundImage1']),
            $this->formatFilePathInTpl($this->_xml->mods['backgroundImage2']),
            $this->formatFilePathInTpl($this->_xml->mods['backgroundImage3'])
        );
        $recordInfo['logo_upload_small']    = $this->genThumbImagePath($this->_xml->mods['myLogo']);
        $recordInfo['bg_upload_small']   = array(
            $this->genThumbImagePath($this->_xml->mods['backgroundImage1']),
            $this->genThumbImagePath($this->_xml->mods['backgroundImage2']),
            $this->genThumbImagePath($this->_xml->mods['backgroundImage3']),
        );

        $recordInfo['mult_bg']      = $this->_xml->mods['multipleBackgrounds'];
        $recordInfo['bg_music']     = $this->_xml->mods['backgroundMusic'];
        $recordInfo['music_upload'] = $this->formatFilePathInTpl($this->_xml->mods['myMusic']);
        $recordInfo['company_info'] = $this->_xml->footerInfo[0];
        
        return $recordInfo;
    }

    //生成
    public function genThumbImagePath($srcImagePath) {
        return $this->formatFilePathInTpl($this->genThumbImageName($srcImagePath)) . self::$infoImgType . '.' . self::$thumbImgInfo[self::$infoImgType]['t']; 
    }
  
    public function getUploadDir() {
        return preg_replace('/public/i', '', $this->_uploadDir);
    }

    //上传文件方法
    protected function uploadFile($fileInfo) {
        if(!empty($fileInfo['name'])) {
            $uploadFile     = new UploadFile($fileInfo,
                                        $this->_uploadDir,
                                        $this->_imageTypes,
                                        $this->_imageSize);
            if(false === $uploadFile->upload()) {
                $this->_error->setErrorInfo($uploadFile->getError());
                Logger::log($uploadFile->getError());
                return '';
            }
            //$arrPath    = explode('/', $uploadFile->getUploadFilePath());
            //$imagePath  = array_pop($arrPath);

            //生成缩略图
            $this->genThumbImage($uploadFile->getUploadFilePath());
            
            return $uploadFile->getUploadFilePath();
        }

        return true;
    }

    //生成缩略图
    protected function genThumbImage($srcFilePath) {
        $thumbImgName  = $this->genThumbImageName($srcFilePath);
        foreach(self::$thumbImgInfo as $kind => $thumbInfo) {
            $thumbImgPath   = $thumbImgName . $kind . '.' . $thumbInfo['t'];
            $genResult      = Image::thumb($srcFilePath, $thumbImgPath, $thumbInfo['t'], $thumbInfo['w'], $thumbInfo['h'], $thumbInfo['i']);
            if(!$genResult) {
               //log 
            }
        } 
    }

    //得到缩略图的路径及文件名
    public function genThumbImageName($srcFilePath) {
        return mb_substr($srcFilePath , 0, strrpos($srcFilePath, '.'), 'utf-8');
    }

    //这个将会作为一个interface
    protected function deleteFile($filePath) {
        if(is_file($filePath) && file_exists($filePath)) {
            $this->delThumbImageFile($filePath);
            return LittleTools::deleteFile($filePath);
        }

        return true;
    }

    //删除相关缩略图
    protected function delThumbImageFile($filePath) {
        $thumbImgName  = $this->genThumbImageName($filePath);
        foreach(self::$thumbImgInfo as $kind => $thumbInfo) {
            $thumbImgPath   = $thumbImgName . $kind . '.' . $thumbInfo['t'];
            LittleTools::deleteFile($thumbImgPath);
        } 
    }

}

?>
